// Set entity data to model properties
var mapper = {
	category: function (entity) {
        var item = new StatusModel();
        //item.response(entity.response);
        item.responseCode(entity.response_code);
		var categoryListResult = ko.observableArray([]);
        _.each(entity.category, function (i) {
            if (i.subcategory.length > 0){
                var categoryItem = new CategoryModel();
                categoryItem.id(mapper.stringByAccepted(i.id));
                categoryItem.caption(mapper.stringByAccepted(i.caption));
                _.each(i.subcategory, function (sub) {
                    var newSub = new SubCategoryModel();
                    newSub.id(mapper.stringByAccepted(sub.id));
                    newSub.caption(mapper.stringByAccepted(sub.caption));
                    categoryItem.subCateList.push(newSub);
                });

                categoryListResult.push(categoryItem);
            }
        });
        item.object = categoryListResult();
        
        return item;

	},

	overview: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		var overviewListResult = ko.observableArray([]);
        
        _.each(entity.summaries, function (i) {
            var overviewItem = new BookModel();
            overviewItem.overView.dataId(mapper.stringByAccepted(i.data_id));
            overviewItem.overView.title(mapper.stringByAccepted(i.title));
            overviewItem.overView.language(mapper.stringByAccepted(i.language));
            overviewItem.overView.thumbnail(mapper.stringByAccepted(i.thumbnail));
            localStore.choosePath(overviewItem.overView.thumbnailMediumDisplay, i.thumbnail_medium);
            overviewItem.overView.thumbnailMedium(mapper.stringByAccepted(i.thumbnail_medium));
            overviewItem.overView.author(mapper.stringByAccepted(i.author));
            overviewItem.overView.extraText(mapper.stripHTML(mapper.stringByAccepted(i.extra_text)));
            overviewItem.overView.subExtraText(mapper.getSubString(mapper.stripHTML(mapper.stringByAccepted(i.extra_text)), overviewItem.overView.language()));
            overviewItem.overView.year(mapper.stringByAccepted(i.year));
            overviewListResult.push(overviewItem);
        });
		

        item.object = overviewListResult;
		return item;
	},

	overviewStartPage: function (entity) {
		var item = new BookModel();
		item.overView.dataId(mapper.stringByAccepted(entity.dataId));
		item.overView.title(mapper.stringByAccepted(entity.title));
		item.overView.language(mapper.stringByAccepted(entity.languageIsoCode));
		item.overView.thumbnail(mapper.stringByAccepted(entity.flashFile));
		localStore.choosePath(item.overView.thumbnailMediumDisplay, mapper.stringByAccepted(entity.flashFile));
		item.overView.thumbnailMedium(mapper.stringByAccepted(entity.flashFile));
		item.overView.author(mapper.stringByAccepted(entity.author));
		item.overView.extraText(mapper.stripHTML(mapper.stringByAccepted(entity.publisher)));
		item.overView.subExtraText(mapper.getSubString(mapper.stripHTML(mapper.stringByAccepted(entity.publisher)), item.overView.language()));
		item.overView.year(mapper.stringByAccepted(entity.year));
		return item;
	},

	favorite: function (entity) {
	},

	book: function (entity) {
        
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        
		var bookItem = new BookModel();
        /* root */
        bookItem.overView.numberAnnotations(mapper.intByAccepted(entity.number_annotations));
        bookItem.overView.downloadsAvailable(mapper.intByAccepted(entity.downloads_available));
        bookItem.overView.preview(mapper.boolByAccepted(entity.preview));
        bookItem.overView.numberComment(mapper.intByAccepted(entity.number_comments));
        if (bookItem.overView.numberComment() == undefined) {
            bookItem.overView.numberComment(0);
        }
        
        
        if (entity.header != undefined){
            var strExtraText = mapper.stringByAccepted(entity.header.extra_text);
            bookItem.overView.title(mapper.stringByAccepted(entity.header.title));
            bookItem.overView.language(mapper.stringByAccepted(entity.header.language));
            bookItem.overView.extraText(mapper.stripHTML(strExtraText));
            bookItem.overView.subExtraText(mapper.getSubString(mapper.stripHTML(strExtraText), bookItem.overView.language()));
            bookItem.overView.author(mapper.stringByAccepted(entity.header.authors_last_name_first));
            bookItem.overView.thumbnail(mapper.stringByAccepted(entity.header.cover_file));
            bookItem.header.year(mapper.stringByAccepted(entity.header.year));
            bookItem.overView.thumbnailMedium(mapper.stringByAccepted(entity.header.cover_file));
            bookItem.header.thumbnailMedium(mapper.stringByAccepted(entity.header.cover_file));
            localStore.choosePath(bookItem.overView.thumbnailMediumDisplay, mapper.stringByAccepted(entity.header.cover_file));
            /* handle later */
            
            bookItem.header.title(mapper.stringByAccepted(entity.header.title));
            bookItem.header.language(mapper.stringByAccepted(entity.header.language));
            if (entity.header.publisher != undefined) {
                bookItem.header.extraText(mapper.stripHTML(mapper.stringByAccepted(entity.header.publisher)));
            }
            
            if (entity.header.full_text != undefined){
                bookItem.header.fullText.text(mapper.stringByAccepted(entity.header.full_text.text));
                bookItem.header.fullText.type(mapper.stringByAccepted(entity.header.full_text.type));
            }
            
            bookItem.header.subExtraText(mapper.getSubString(mapper.stripHTML(strExtraText), bookItem.header.language()));
            bookItem.header.subtitle(mapper.stringByAccepted(entity.header.subtitle));
            bookItem.header.audioFile(mapper.stringByAccepted(entity.header.audio_file));
            bookItem.header.authorsLastNameFirst(mapper.stringByAccepted(entity.header.authors_last_name_first));
        }
		
        
        /* abstract parser */
		if (entity.abstract != undefined) {
			bookItem.abstract.title(mapper.stringByAccepted(entity.abstract.title));
			bookItem.abstract.text(mapper.stringByAccepted(entity.abstract.text));
		}
        /* author parser */
        if (entity.about_author != undefined){
            bookItem.aboutAuthor.text(mapper.stringByAccepted(entity.about_author.text));
            bookItem.aboutAuthor.title(mapper.stringByAccepted(entity.about_author.title));
        }
		/* relevance parser */
        if (entity.relevance != undefined){
            if (entity.relevance.recommendation != undefined){
                bookItem.relevance.recommendation.text(mapper.stringByAccepted(entity.relevance.recommendation.text));
                bookItem.relevance.recommendation.title(mapper.stringByAccepted(entity.relevance.recommendation.title));
            }
            if (entity.relevance.learntopics != undefined){
                bookItem.relevance.title(mapper.stringByAccepted(entity.relevance.title));
                bookItem.relevance.learnintro(mapper.stringByAccepted(entity.relevance.learnintro));
                if (entity.relevance.learntopics != undefined){
                    _.each(entity.relevance.learntopics, function (i) {
                           bookItem.relevance.learntopics.push(i);
                           });
                }
            }
        }
		
        /* take aways parser */
		if (entity.takeaways != undefined) {
			bookItem.takeAway.title(mapper.stringByAccepted(entity.takeaways.title));
            if (entity.takeaways.takeaways != undefined){
                bookItem.takeAway.takeaways(mapper.stringByAccepted(entity.takeaways.takeaways));
            }
		}
        
        /* Ratings parser */
        if (entity.ratings != undefined){
            bookItem.rating.subtitle(mapper.stringByAccepted(entity.ratings.subtitle));
            if (entity.ratings.rating != undefined){
                var flag = false;
                _.each(entity.ratings.rating, function (i) {
                    var ratingTemp = mapper.intByAccepted(i.value);
                    var sequenceTemp = mapper.intByAccepted(i.sequence);

                    if (sequenceTemp == 1 && ratingTemp == -1){
                    /* Overal field has value is -1 */
                    flag = true;
                    }
                    bookItem.rating.ratings.push(i);
                });
                if (flag){
                    /* remove all object */
                    bookItem.rating.ratings([]);
                }
            }
            
        }
		/* Quotes paser */
        if (entity.quotes != undefined){
            bookItem.quote.title(mapper.stringByAccepted(entity.quotes.title));
            if (entity.quotes.quotes != undefined){
                _.each(entity.quotes.quotes, function (i) {
                       bookItem.quote.quotes.push(i);
                       });
            }
        }
		
        item.object = bookItem;
        
		return item;
	},

	status: function (entity) {
        
		var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		return item;
	},
    user: function (entity){

        var item = new StatusModel();
        
        item.response('OK');
        item.responseCode(0);
        
        var user = new UserModel();
        
        user.accessToken(entity.access_token);
        user.refreshToken(entity.refresh_token);
        
        item.object = user;

		return item;
    },

	getSetting: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        var settingItem = new SettingsModel();
        
        
		_.each(entity.summary_groups, function (i) {
                   var sg = new summaryGroupModel();
                   sg.id(i.group_id);
                   sg.name(i.name);
                   _.each(i.language_options, function (o) {
                          console.log(3);
                          var op = new laguageOptionItemsModel();
                          op.name(o.name);
                          op.symbol(o.iso_code);
                          op.active(o.active);
                          sg.languageOptions.push(op);
                          });
                   settingItem.summaryGroup.push(sg);
               });
        item.object = settingItem;
        return item;
        
	},

	start: function (entity) {
		var item = new StartModel();
		if (Object.prototype.toString.call(entity.category) === '[object Array]') {
			_.each(entity.category, function (i) {
				var sc = new startCategoryModel();
				sc.id(i.categoryId);
				sc.title(i.title);
				if (Object.prototype.toString.call(i.summaries.summary) === '[object Array]') {
					_.each(i.summaries.summary, function (o) {
						var ss = new startSummaryModel();
						ss.id(o.dataId);
						ss.title(o.title);
						ss.author(o.author);
						ss.coverURL(o.flashfile);
						localStore.choosePath(ss.coverURLDisplay, o.flashfile);
						sc.summaries.push(ss);
					});
				} else if (i.summaries.summary != undefined) {
					var ss = new startSummaryModel();
					ss.id(o.dataId);
					ss.title(o.title);
					ss.author(o.author);
					ss.coverURL(o.flashfile);
					localStore.choosePath(ss.coverURLDisplay, o.flashfile);
					sc.summaries.push(ss);
				}
				item.categories.push(sc);
			});
		} else if (entity.category != undefined) {
			var sc = new startCategoryModel();
			sc.id(entity.category.categoryId);
			sc.title(entity.category.title);
			if (Object.prototype.toString.call(entity.category.summaries.summary) === '[object Array]') {
				_.each(entity.category.summaries.summary, function (o) {
					var ss = new startSummaryModel();
					ss.id(o.dataId);
					ss.title(o.title);
					ss.author(o.author);
					ss.coverURL(o.flashfile);
					localStore.choosePath(ss.coverURLDisplay, o.flashfile);
					sc.summaries.push(ss);
				});
			} else if (entity.category.summaries.summary != undefined) {
				var ss = new startSummaryModel();
				ss.id(entity.category.summaries.summary.name.dataId);
				ss.title(entity.category.summaries.summary.name.title);
				ss.author(entity.category.summaries.summary.name.author);
				ss.coverURL(entity.category.summaries.summary.name.flashfile);
				localStore.choosePath(ss.coverURLDisplay, entity.category.summaries.summary.name.flashfile);
				sc.summaries.push(ss);
			}
			item.summaryGroup.push(sc);
		}

		return item;
	},

	startPage: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        var startItem = new StartModel();
		_.each(entity.list, function (i) {
               if (i.summary.length > 0) {
               var sc = new startCategoryModel();
               sc.id(i.list_id);
               sc.title(i.title);
               sc.subtitle(i.subtitle);
               _.each(i.summary, function (o) {
                      var ss = new startSummaryModel();
                      ss.id(o.data_id);
                      ss.listId(i.list_id);
                      ss.title(mapper.getSubString(o.title, systemLanguage, 80));
                      ss.author(o.author);
                      ss.coverURL(o.cover_file);
                      localStore.choosePath(ss.coverURLDisplay, o.cover_file);
                      sc.summaries.push(ss);
                      });
               
               startItem.categories.push(sc);
               }
               });
        item.object = startItem;
        return item;


	},

	startPageSetting: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		var settingListResult = ko.observableArray([]);
		var i = 0;
		_.each(entity.list, function (o) {
			var ss = new SettingsOfStartModel();
			ss.listId(o.list_id);
			ss.title(o.title);
			ss.active(o.active);
			ss.viewAll(o.view_all);
			ss.index(i);
			settingListResult.push(ss);
			i++;
		});
        item.object = settingListResult;
		return item;
	},

	startPageSettingPost: function (entity) {
        
		var item = new StatusModel();
		item.statusCode(entity.error_code);
		item.statusMessage(entity.message);
		item.statusSuccess(entity.success);
		return item;
	},

	favoriteFolder: function (entity) {
        
        var item = new StatusModel();
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        var favoriteFolderList = ko.observableArray([]);
        if (entity.folder != undefined){
            _.each(entity.folder, function (i) {
                   var itemFolder = new FavoriteFolderItem();
                   itemFolder.folderID(mapper.stringByAccepted(i.id));
                   itemFolder.folderName(mapper.stringByAccepted(i.name));
                   
                   if (itemFolder.folderName().length == 0){
                        itemFolder.folderName(getLocalizeText('defaultFolder'));
                   }
                   
                   favoriteFolderList.push(itemFolder);
                   });
        }
        item.object = favoriteFolderList;
		return item;
	},

	addFavorite: function (entity) {
		var item = new StatusModel();
		item.statusMessage(entity.success);

		return item;
	},

	syncFavorite: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		var favoriteList = ko.observableArray([]);
        _.each(entity.folder, function (i) {
               _.each(i.favorites, function (item) {
                      var itemfavorite = new FavoriteItem();
                      itemfavorite.folderID(i.id);
                      itemfavorite.itemID(item.data_id);
                      favoriteList.push(itemfavorite);
                      });
        });
        item.object = favoriteList;
        
        return item;
	},

	active: function (entity) {
        var item = new StatusModel();
        
	},

	buythebook: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		item.object = mapper.stringByAccepted(entity.html);

		return item;
	},

	comments: function (entity) {
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        var commentList = ko.observableArray([]);
        
        _.each(entity.comment, function (i) {

            if (i.text != null) {
                var commentItem = new CommentModel();
                commentItem.date(mapper.dateFromMilliseconds(i.date));
                commentItem.name(i.name);
                commentItem.text(i.text);
                commentList.push(commentItem);
            }
        });
        
        item.object = commentList;
        return item;
	},

	annotations: function (entity) {
        var item = new StatusModel();
        
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
		var annotationListResult = ko.observableArray([]);
        
        _.each(entity.comments, function (i) {
               var annotationItem = new CommentModel();
               annotationItem.text(i);
               annotationListResult.push(annotationItem);
               });
        item.object = annotationListResult;
		return item;
	},

	postComments: function (entity) {
		var item = new StatusModel();
		item.statusMessage(entity.success);
		return item;
	},

	postShareEmail: function (entity) {
		var item = new StatusModel();
		item.statusMessage(entity.success);
		return item;
	},

	about: function (entity) {
        
        var item = new StatusModel();
        
        //item.response(entity.response);
        item.responseCode(entity.response_code);
        
        var aboutItem = new AboutModel();
        
        aboutItem.title(mapper.stringByAccepted(entity.title));
		aboutItem.description(mapper.stringByAccepted(entity.content));
        
        item.object = aboutItem;
        
		return item;
	},

    refreshToken: function (entity) {
        var item = new StatusModel();

        //item.response(entity.response);
        item.responseCode(entity.response_code);

        var user = new UserModel();

        user.accessToken(entity.accessToken);

        item.object = user;

		return item;
	},

	numberFreeBook: function (entity) {
		if (entity.businessSummaries != undefined) {
			return entity.businessSummaries;
		}
		return 0;
	},

	toError: function (entity) {
		var item = new ErrorModel();
        
        /* login error check */
        if (entity.error_description != undefined){
            item.errorMessage(entity.error_description);
            item.displayError(entity.error);
            item.responseCode(-1);
        }
        else{
            /* is normal error */
            item.errorMessage(entity.error_message);
            item.displayError(entity.display_error);
            item.responseCode(entity.response_code);
        }
        
        
		return item;
	},

	getSubString: function (strFather, language, maxWidthInput) {
		var maxWidth = maxWidthInput;
		if (!maxWidthInput) {
			maxWidth = $(window).width() - 130;
		}
		var strResult = "";
		if (language == "zh" || language == "ZH") {
			if (strFather.length > 2 * maxWidth / 12.6) {
				return strFather.substring(0, 2 * maxWidth / 12.6) + "...";
			} else {
				return strFather;
			}
		}

		var n = strFather.split(" ");
		var width1 = 0;
		var width2 = 0;
		for (i = 0; i < n.length; i++) {
			if (width1 != -1 && width1 + (n[i].length * 6) < maxWidth) {
				width1 += (n[i].length + 1) * 6;
			} else {
				width1 = -1;
				if (width2 != -1 && width2 + (n[i].length * 6) < maxWidth) {
					width2 += (n[i].length + 1) * 6;
				} else {
					strResult += "...";
					break;
				}
			}

			strResult += n[i] + " ";
		}
        /* check if work too short, same as 'Die...', '...' */
        if (strResult.length < 15 && strFather.length > 15){
            strResult = strFather.substr(0, 15) + "...";
        }
        
		return strResult;
	},

	stripHTML: function (html) {
		return html.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi, '');
	},

	dateFromMilliseconds: function (miliseconds) {
		if (miliseconds == null || miliseconds <= 0) {
			return "";
		}

		var d = new Date();
		var m_names = new Array(getLocalizeText('jan'), getLocalizeText('feb'), getLocalizeText('mar'),
			getLocalizeText('apr'), getLocalizeText('may'), getLocalizeText('jun'), getLocalizeText('jul'), getLocalizeText('aug'), getLocalizeText('sep'),
			getLocalizeText('oct'), getLocalizeText('nov'), getLocalizeText('dec'));
		d.setTime(miliseconds);
		var curr_date = d.getDate();
		var curr_month = d.getMonth();
		var curr_year = d.getFullYear();

		return curr_date + ' ' + m_names[curr_month] + ' ' + curr_year;
	},
    stringByAccepted: function(value){
        if (value != undefined){
            return value;
        }
        return "";
    },
    intByAccepted: function(value){
        if (value != undefined){
            return value;
        }
        return -1;
    },
    boolByAccepted: function(value){
        if (value != undefined){
            if (value == true || value == 'true'){
                return true;
            }
        }
        return false;
    }
}
